package ma.jeetconsulting.pocs.service;

import static ma.jeetconsulting.pocs.service.Utils.getPomObjectModel;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.maven.model.Dependency;
import org.apache.maven.model.Model;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;

import freemarker.template.TemplateException;

public class ProjectService {

	private List<ModuleReport> reports = new ArrayList<>();
	private ObsoleteDependenciesDetector detector;
	private CodeAnalyzer analyzer;
	private String projectPath;
	private Reporter reporter;

	public ProjectService(String projectPath) {
		this.projectPath = projectPath;
	}

	public String getProjectPath() {
		return projectPath;
	}

	public void setProjectPath(String projectPath) {
		this.projectPath = projectPath;
	}

	public void checkAndAlertObsoleteDependencies() {
		
		List<String> modules;
		try {
			modules = getModules(projectPath);
			if(modules != null) {
				for (String moduleName : modules) {
					String modulePath = projectPath + File.separator + moduleName;
					makeObsoloteDependecyReportFor(moduleName, modulePath);
				}
			} else {
				makeObsoloteDependecyReportFor(getPomObjectModel(projectPath).getArtifactId(), projectPath);
			}
			reporter.makeReport(reports);
		} catch (IOException | XmlPullParserException | TemplateException e) {
			e.printStackTrace();
		}
		
	}

	private void makeObsoloteDependecyReportFor(String moduleName,
			String modulePath) {
		ModuleAnalyzer moduleAnalyzer = new ModuleAnalyzer();
		List<Dependency> dependencies = moduleAnalyzer.getDependencies(modulePath);
		List<Dependency> obsoleteDependencies = detector.checkForObsoleteDependencies(dependencies);
		if(obsoleteDependencies.size() != 0) {
			ModuleReport moduleReport = analyzer.makeObsoleteDependenciesReportFor(obsoleteDependencies, modulePath);
			moduleReport.setModuleName(moduleName);
			reports.add(moduleReport);
		}
	}
	
	public void setReporter(Reporter reporter) {
		this.reporter = reporter;
	}

	public void setObsoleteDependenciesDetector(ObsoleteDependenciesDetector detector) {
		this.detector = detector;
	}

	public void setProjectAnalyzer(CodeAnalyzer analyzer) {
		this.analyzer = analyzer;
		
	}
	private List<String> getModules(String projectRootPath) 
			throws FileNotFoundException, IOException, org.codehaus.plexus.util.xml.pull.XmlPullParserException {
		Model pomModel = Utils.getPomObjectModel(projectRootPath);
		if (!pomModel.getModules().isEmpty()){
			return pomModel.getModules();
		} else {
			return null;
		}
	}
	
}
